package com.thread;

/**
 * @author: mayu
 * @date: 2021年04月07日 16:02
 * DCL单例需要加volatile，防止指令重排序
 */
public class DCLSingleton {
    private static volatile DCLSingleton INSTANCE;

    private DCLSingleton() {
    }

    public static DCLSingleton getInstance() {
        if (INSTANCE == null) {//一开始不用获取锁，提高效率
            synchronized (DCLSingleton.class) {
                if (INSTANCE == null) {//不加二次判断，会new多次，产生多个实例
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    INSTANCE = new DCLSingleton();
                }
            }
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                System.out.println(DCLSingleton.getInstance().hashCode());
            }).start();
        }
    }
}
